package com.stars.easyms.base.util;

import java.util.Collection;
import java.util.LinkedList;

/**
 * <p>className: FIFOList</p>
 * <p>description: FIFO：First In First Out，先进先出。判断被存储的时间，离目前最远的数据优先被淘汰。</p>
 *
 * @author guoguifang
 * @date 2019-10-17 11:55
 * @since 1.3.3
 */
public class FIFOList<E> extends LinkedList<E> {

    private final int limit;

    public FIFOList(int limit) {
        this.limit = limit;
    }

    @Override
    public boolean add(E e) {
        super.add(e);
        while (size() > limit) {
            removeFirst();
        }
        return true;
    }

    @Override
    public void add(int index, E e) {
        super.add(index, e);
        while (size() > limit) {
            removeFirst();
        }
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        if (!c.isEmpty()) {
            super.addAll(c);
            while (size() > limit) {
                removeFirst();
            }
        }
        return true;
    }

    @Override
    public boolean addAll(int index, Collection<? extends E> c) {
        if (!c.isEmpty()) {
            super.addAll(index, c);
            while (size() > limit) {
                removeFirst();
            }
        }
        return true;
    }

    @Override
    public void addFirst(E e) {
        if (size() < limit) {
            super.addFirst(e);
        }
    }

    @Override
    public void addLast(E e) {
        add(e);
    }
}